/**
 * client-side cookie
 */
export function cookies(doc) {
  if (!doc) doc = {};
  if (typeof doc === 'string') doc = { cookie: doc };
  if (doc.cookie === undefined) doc.cookie = '';

  return {
    get(key) {
      const splat = doc.cookie.split(/;\s*/);
      for (let i = 0; i < splat.length; i++) {
        const ps = splat[i].split('=');
        const k = unescape(ps[0]);
        if (k === key) return unescape(ps[1]);
      }
      return undefined;
    },
    set(key, value, opts = {}) {
      let s = escape(key) + '=' + escape(value);
      if (opts.path) s += '; path=' + escape(opts.path);
      if (opts.domain) s += '; domain=' + escape(opts.domain);
      if (opts.expires) s += '; expires=' + opts.expires.toUTCString();
      if (opts.maxAge) s += '; max-age=' + opts.maxAge;
      if (opts.samesite) s += '; samesite=' + opts.samesite;
      if (opts.secure) s += '; secure';
      doc.cookie = s;
      return s;
    },
  };
}
